import streamlit as st
from openai import OpenAI
import datetime

# ========== 页面配置 ==========
st.set_page_config(page_title="智能聊天问答系统", page_icon="💬", layout="wide")
st.title("💬 智能聊天问答系统")
st.caption("作者：何双新 ｜ 技术栈： Openai + Streamlit")

# ========== OpenAI Client ==========
client = OpenAI(
    api_key="sk-8569c070be3b49f4a8c01d3a88d1989b",  # 请替换为你自己的 API Key
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)

# ========== 聊天角色设定 ==========
roles = {
    "默认助手": "你是一个乐于助人的助手。",
    "专业医生": "你是一个细心、专业的医生，擅长给出健康建议。",
    "英语老师": "你是一个耐心的英语老师，擅长解释语言知识。",
    "程序员助手": "你是一个资深程序员，擅长解答编程相关问题。"
}

# ========== 初始化会话状态 ==========
if "messages" not in st.session_state:
    st.session_state.messages = []
if "system_role" not in st.session_state:
    st.session_state.system_role = list(roles.values())[0]
if "welcomed" not in st.session_state:
    st.session_state.welcomed = False

# ========== 侧边栏 ==========
with st.sidebar:
    st.title("⚙️ 配置")

    role_choice = st.selectbox("选择聊天角色", list(roles.keys()))
    st.session_state.system_role = roles[role_choice]

    if st.button("💾 保存聊天记录"):
        if st.session_state.messages:
            now = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"chat_history_{now}.txt"
            with open(filename, "w", encoding="utf-8") as f:
                for chat in st.session_state.messages:
                    f.write(f"{chat['role'].capitalize()}: {chat['content']}\n\n")
            st.success(f"聊天记录已保存到 {filename}")
        else:
            st.warning("当前没有聊天记录可以保存。")

    st.markdown("---")
    st.markdown("🔔 请合理使用，避免发送敏感信息。")



# ========== 页面标题 ==========

# ========== 欢迎提示 ==========
if not st.session_state.welcomed:
    st.markdown("""
    <div style="
        background-color: #042038;
        padding: 1.2rem;
        border-radius: 0.75rem;
        margin-bottom: 1rem;
        color:white;
        border-left: 6px solid #1b5288;
    ">
        <h3>👋 欢迎使用 <strong>Melon 聊天助手</strong>！</h3>
        <p>我可以帮助你回答各种问题，支持 <code>Markdown</code> 输出、代码、表格等。</p>
        <p>试试输入：<code>制定一个健康管理计划</code> 或 <code>解释 Python 中的装饰器</code></p>
    </div>
    """, unsafe_allow_html=True)
    st.session_state.welcomed = True

# ========== 自定义气泡渲染函数 ==========
def render_user_message(content: str, key: str):
    st.markdown(f"""
    <div style="display: flex; justify-content: flex-end; margin: 0.5rem 0;">
        <div class="user-bubble" style="
            background-color: #042038;
            padding: 1rem;
            border-radius: 0.75rem;
            max-width: 85%;
             color:white;
            border-left: 6px solid #1b5288;
        ">{content}</div>
        <div style="font-size: 1.5rem; margin-left: 0.5rem;">👤</div>
    </div>
    """, unsafe_allow_html=True)

def render_ai_message(content: str, key: str):
    st.markdown(f"""
    <div style="display: flex; align-items: flex-start; margin: 0.5rem 0;">
        <div style="font-size: 1.5rem; margin-right: 0.5rem;">🤖</div>
        <div class="ai-bubble" style="
            background-color: #042038;
            padding: 1rem;
            border-radius: 0.75rem;
            max-width: 85%;
            color:white;
            border-left: 6px solid #1b5288;
        ">{content}</div>
    </div>
    """, unsafe_allow_html=True)


# ========== 渲染历史消息 ==========
for i, chat in enumerate(st.session_state.messages):
    if chat["role"] == "user":
        render_user_message(chat["content"], key=str(i))
    else:
        render_ai_message(chat["content"], key=str(i))

# ========== 聊天输入 ==========
with st.form("chat_input_form", clear_on_submit=True):
    user_input = st.text_input("输入你的问题", placeholder="请在这里提问...", label_visibility="collapsed")
    submitted = st.form_submit_button("发送")

# ========== LLM 处理 ==========
if submitted and user_input:
    st.session_state.messages.append({"role": "user", "content": user_input})

    prompt_messages = [{"role": "system", "content": st.session_state.system_role}]
    prompt_messages += [{"role": msg["role"], "content": msg["content"]} for msg in st.session_state.messages]

    with st.spinner("思考中..."):
        try:
            response = client.chat.completions.create(
                model="qwen-turbo",
                messages=prompt_messages,
                temperature=0.7,
            )
            bot_reply = response.choices[0].message.content.strip()
        except Exception as e:
            bot_reply = f"❌ 出错了：{e}"

    st.session_state.messages.append({"role": "assistant", "content": bot_reply})
    render_ai_message(bot_reply, key=f"reply-{len(st.session_state.messages)}")
st.caption("安徽智加数字科技有限公司 · 技术学习组出品 🚀")
